using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Process;

namespace WPF_MVVM_Test.Services.Process
{
    /// <summary>
    /// 工序服务类
    /// </summary>
    public class ProcessStepService
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl = "http://8.140.242.140:8888/api/Bom/routing";

        public ProcessStepService()
        {
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 根据工艺路线ID获取工序列表
        /// </summary>
        /// <param name="processRouteId">工艺路线ID</param>
        /// <returns></returns>
        public async Task<ProcessStepApiResponse> GetProcessStepsByRouteIdAsync(string processRouteId)
        {
            try
            {
                var url = $"{_baseUrl}/{processRouteId}/processes";

                System.Diagnostics.Debug.WriteLine($"请求工序数据，URL: {url}");

                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    
                    System.Diagnostics.Debug.WriteLine($"工序API响应: {jsonString}");

                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };

                    var result = JsonSerializer.Deserialize<ProcessStepApiResponse>(jsonString, options);

                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"工序数据解析成功，数据数量: {result.Data?.Count ?? 0}");
                        return result;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("工序数据解析失败，返回空结果");
                        return new ProcessStepApiResponse
                        {
                            IsSuc = false,
                            Code = 500,
                            Msg = "数据解析失败"
                        };
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"工序API请求失败，状态码: {response.StatusCode}");
                    return new ProcessStepApiResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"工序API请求异常: {ex.Message}");
                return new ProcessStepApiResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 根据工序ID获取物料列表 - 每次都从数据库获取最新数据
        /// </summary>
        /// <param name="processStepId">工序ID</param>
        /// <returns></returns>
        public async Task<ProcessStepMaterialApiResponse> GetProcessStepMaterialsAsync(string processStepId)
        {
            try
            {
                // 添加时间戳参数防止缓存，确保每次都获取最新数据
                var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                var url = $"http://8.140.242.140:8888/api/Bom/process/{processStepId}/materials";

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 请求工序物料数据，URL: {url}");

                // 设置请求头，确保不使用缓存
                _httpClient.DefaultRequestHeaders.Remove("Cache-Control");
                _httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store, must-revalidate");
                _httpClient.DefaultRequestHeaders.Remove("Pragma");
                _httpClient.DefaultRequestHeaders.Add("Pragma", "no-cache");

                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    
                    System.Diagnostics.Debug.WriteLine($"工序物料API响应: {jsonString}");

                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };

                    var result = JsonSerializer.Deserialize<ProcessStepMaterialApiResponse>(jsonString, options);

                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"工序物料数据解析成功，数据数量: {result.Data?.Count ?? 0}");
                        return result;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("工序物料数据解析失败，返回空结果");
                        return new ProcessStepMaterialApiResponse
                        {
                            IsSuc = false,
                            Code = 500,
                            Msg = "数据解析失败"
                        };
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"工序物料API请求失败，状态码: {response.StatusCode}");
                    return new ProcessStepMaterialApiResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"工序物料API请求异常: {ex.Message}");
                return new ProcessStepMaterialApiResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}